import { getToken } from '@/utils/auth'
import { getUserInfo ,getCurrentRoutes ,refreshToken} from '@/api/authority/User'

const state = {
  token: getToken(),
  user: {},
  roles: [],
  // 第一次加载菜单时用到
  loadMenus: false
}
const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER: (state, user) => {
    state.user = user
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_LOAD_MENUS: (state, loadMenus) => {
    state.loadMenus = loadMenus
  }
}
const actions = {
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
    })
  },
  // 获取用户信息
  getUserInfo({ commit }, payload) {
    return new Promise((resolve, reject) => {
      getUserInfo(payload).then(res => {
        if (res.code===200) {
          commit('SET_USER', res.data)
          resolve(res)
        } else {
          reject(res.msg)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 登出
  logout({ commit }) {
    return new Promise((resolve, reject) => {
      window.localStorage.clear()
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve, reject) => {
      window.localStorage.clear()
      resolve()
    })
  },
  //  获取用户菜单权限
  getCurrentRoutes({ commit }, payload) {
    return new Promise((resolve, reject) => {
      getCurrentRoutes(payload).then(res => {
        if (res.code ===200) {
          resolve(res.data)
        } else {
          reject(res.message)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  refreshToken({ commit }, payload) {
    return new Promise((resolve, reject) => {
      refreshToken(payload).then(res => {
        debugger
        if (res.code===200) {
          commit('SET_USER', res.data)
          resolve(res)
        } else {
          reject(res.msg)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
